<?php
/**
 * Created by PhpStorm.
 * User: zhaiyujin
 * Date: 19-8-28
 * Time: 上午11:57
 */
namespace App\Http\Middleware;

use Closure;
use function dump;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use function var_dump;

class CheckToken extends BaseMiddleware
{
    /**
     * @author: zhaiyujin
     * @param $request
     * @param Closure $next
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response|mixed
     * @throws JWTException
     */
    public function handle($request, Closure $next,$guard=null)
    {

        try {
            // 检查此次请求头中是否带有 token，如果没有则抛出异常。
            $this->checkForToken($request);

            if (!$user = JWTAuth::toUser(JWTAuth::getToken())){
                return response()->json([
                    'status' => 401,
                    'message' => '无此用户'
                ], 401);
            }

            //判断角色
            /*$userCustom=$user->getJWTCustomClaims();
            if($userCustom['role']=="merchant"){
                if($user->hasRole('admin'))  return $next($request);
                //判断权限
                if (!$user->can($request->route()->getName()))
                    return response()->json([
                        'status' => 401,
                        'message' => '没有操作权限'
                    ], 401);
            }*/
        } catch (TokenExpiredException $e) {


            #异常处理 token过有效期,进行刷新
            try{

                $token = JWTAuth::refresh();
                $access_token = 'Bearer'.$token;
                $request->headers->set('Authorization',$access_token);
            }catch(JWTException $exception){
                #refresh 也过期,重新登录
                return response()->json([
                    'status' => 402,
                    'message' => 'token 过期'
                ], 402);
            }


            return response()->json([
                'status' => 402,
                'message' => 'token 过期'
            ], 402);

        } catch (TokenInvalidException $e) {

            return response()->json([
                'status' => 403,
                'message' => 'token 失效'
            ], 403);

        }catch (AuthenticationException $e) {

            return response()->json([
                'status' => 404,
                'message' => ''.$e->getMessage()
            ]);

        }catch (JWTException $e) {

            return response()->json([
                'status' => 400,
                'message' => 'token 参数错误'
            ]);

        }catch (UnauthorizedHttpException $e){
            return response()->json([
                'status' => 405,
                'message' => '您还没有登录,请先登录'.$e->getMessage()
            ]);
        } catch (\Exception $e){
            return response()->json(['message' => $e->getMessage(),'code'=>$e->getLine(),'file'=>$e->getFile(), 'status' => 500], 500);
        }

        return $next($request);
    }
}